<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-tabs v-model="activeName">
        <el-tab-pane label="登录账户设置" name="account">
          <el-row type="flex" justify="center" style="margin-top:50px">
            <el-form ref="form" label-width="100px" :model="userInfo" :rules="rules">
              <el-form-item label="姓名" style="width:400px" prop="username">
                <el-input v-model="userInfo.username" />
              </el-form-item>
              <el-form-item label="密码" prop="updatedPassword">
                <el-input v-model="userInfo.updatedPassword" type="password" />
              </el-form-item>
              <el-form-item style="margin-top:50px">
                <el-row type="flex" justify="center">
                  <el-button style="margin-right:30px" @click="$router.back()">取消</el-button>
                  <el-button type="primary" @click="saveUserDetailById">更新</el-button>
                </el-row>
              </el-form-item>
            </el-form>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="个人详情" name="userDetail">
          <component :is="userDetail" />
        </el-tab-pane>
        <el-tab-pane label="岗位信息" name="position">
          <component :is="JobInfo" />
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { saveUserDetailById } from '@/api/employees'
import { getUserDetail } from '@/api/user'

import UserInfo from '../components/UserInfo'
import JobInfo from '../components/JobInfo'
export default {
  components: {
    UserInfo,
    JobInfo
  },
  data() {
    const checkPassword = (rule, value, callback) => {
      if (value.length >= 6 && value.length <= 18) {
        callback()
      } else {
        callback(new Error('密码为6-18位'))
      }
    }
    return {
      userDetail: 'UserInfo',
      JobInfo: 'JobInfo',
      activeName: 'account',
      userInfo: {
        username: '',
        updatedPassword: ''
      },
      rules: {
        username: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          { min: 1, max: 4, message: '姓名为1-4位' }
        ],
        updatedPassword: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { trigger: 'blur', validator: checkPassword }
        ]
      }
    }
  },
  created() {
    this.getUserDetail()
  },
  methods: {
    async getUserDetail() {
      try {
        const userData = await getUserDetail(this.$route.params.id)
        this.userInfo = userData
      } catch (error) {
        console.dir(error)
      }
    },
    async saveUserDetailById() {
      try {
        const isValid = await this.$refs.form.validate()
        if (isValid) {
          this.userInfo.password = this.userInfo.updatedPassword
          await saveUserDetailById(this.userInfo)
        }
      } catch (error) {
        console.dir(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
